﻿using System;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Collections;


using MediaPortal.Profile;

namespace MyLeech
{
  public partial class frmSetup : Form
  {
    private ArrayList FILE = new ArrayList();
    private String InputLine = String.Empty;
 
    public frmSetup()
    {
      InitializeComponent();
    }

    private void frmSetup_Load(object sender, EventArgs e)
    {
      Settings mpSettings = new Settings(MediaPortal.Configuration.Config.GetFolder(MediaPortal.Configuration.Config.Dir.Config) + @"\MyLeech.xml");

      // Hellanzb Settings
      // --------------------------------------------------
     
      up_freq_tb.Text = mpSettings.GetValueAsInt("#Hellanzb", "UpFrequency", 5).ToString();
      hella_tb.Text = mpSettings.GetValue("#Hellanzb", "location");
      if (hella_tb.Text.Length < 8)
      {
        if (File.Exists(@"C:\hellanzb\system\hellanzb.py")) hella_tb.Text = @"C:\hellanzb";
        else { hella_tb.Text = @"Find Hellanzb File"; }
      }
      start_hell_chk.Checked = mpSettings.GetValueAsBool("#Hellanzb", "allow_start", true);
      // --------------------------------------------------

      // Plugin Settings
      // --------------------------------------------------
      music_tb.Text = mpSettings.GetValue("#Plugin", "music_folder");
      video_tb.Text = mpSettings.GetValue("#Plugin", "video_folder");
      if (music_tb.Text.Length < 10)
      {
        //find the users video folder
        music_tb.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
      }
      if (video_tb.Text.Length < 10)
      {
        //find the users video folder
        if(Environment.OSVersion.ToString().IndexOf(" 5.") > -1){ video_tb.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+@"\My Videos";}
        if(Environment.OSVersion.ToString().IndexOf(" 6.") > -1){ video_tb.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+@"\Videos";}

      }
      do_move_chk.Checked = mpSettings.GetValueAsBool("#Plugin", "move_files",true);
      
      //LOAD HELLANZB CONFIG SETTINGS
      StreamReader reader = new StreamReader(hella_tb.Text+@"\system\etc\hellanzb.conf");
      string LINE = String.Empty;
      while (!reader.EndOfStream)
      {
        LINE = String.Empty;
        LINE = reader.ReadLine();
        this.FILE.Add(LINE);
        if (LINE.IndexOf("defineServer") > -1)
        {
          string pattern = @"id='(?<part1>.*?)',\shosts=\['(?<part2>.*?):(?<part3>\d{2,3})'\],username='(?<part4>.*?)',\spassword='(?<part5>.*?)',\sconnections=(?<part6>[\d{1,2}]),.*?ssl=(?<part7>.*?)\)";
          Regex regex = new Regex(pattern);
          Match match = regex.Match(LINE);
          while (match.Success)
          {

              server_tb.Text =  match.Groups["part2"].ToString();
              port_tb.Text =  match.Groups["part3"].ToString();
              user_tb.Text =  match.Groups["part4"].ToString();
              pwd_tb.Text =  match.Groups["part5"].ToString();
              connections_combox.SelectedItem = match.Groups["part6"].ToString();
              if (match.Groups["part7"].ToString() == "true") enable_ssl_chk.Checked = true;
              else enable_ssl_chk.Checked = false;

            break;
          }

        }
      }
      reader.Close();
      // --------------------------------------------------
      Sites.HTTP_Common HTTP_Common = new Sites.HTTP_Common();
      string[] AUTO_MOVIE = HTTP_Common.Filters(mpSettings.GetValueAsString("#Filters","auto_movie","DVDRip;DVDScreener;DVD"));
      string[] AUTO_REMOVE = HTTP_Common.Filters(mpSettings.GetValueAsString("#Filters", "auto_remove", "dubbed;german;french;spanish;russian"));
      for (int i = 0; i < AUTO_MOVIE.Length; i++){movie_filter_lb.Items.Add(AUTO_MOVIE[i]);}
      for (int i = 0; i < AUTO_REMOVE.Length; i++) { auto_remove_lb.Items.Add(AUTO_REMOVE[i]); }
      mpSettings.Dispose();
    }

    private void SaveConfig()
    {
      Settings mpSettings = new Settings(MediaPortal.Configuration.Config.GetFolder(MediaPortal.Configuration.Config.Dir.Config) + @"\MyLeech.xml");

      // HellaNZB Settings
      // --------------------------------------------------
      int intUpdateFreq = 5;
      int.TryParse(up_freq_tb.Text, out intUpdateFreq);
      mpSettings.SetValue("#Hellanzb", "UpFrequency", intUpdateFreq);
      if (hella_tb.Text.Length > 0) mpSettings.SetValue("#Hellanzb", "location", hella_tb.Text);
      else { 
        //else see if we can find it
        if (File.Exists(@"C:\hellanzb\system\hellanzb.py")) { mpSettings.SetValue("#Hellanzb", "location", @"C:\hellanzb"); }
        else { MessageBox.Show("Error: Can't Find Hellanzb.py"); }
      }
      if (start_hell_chk.Checked)
      {
        //try find python25
        //DRIVE
        string DRIVE = hella_tb.Text.Substring(0, 3);
        if (File.Exists(DRIVE + @"Python25\pythonw.exe")) { 
          mpSettings.SetValue("#Hellanzb", "python", DRIVE + @"Python25\pythonw.exe");
          mpSettings.SetValueAsBool("#Hellanzb", "allow_start", start_hell_chk.Checked);
        }
        else
        {
          mpSettings.SetValueAsBool("#Hellanzb", "allow_start", false);
          MessageBox.Show(@"Error: Unable to Find Python25\pythonw.exe");
        }
      }
      
      // --------------------------------------------------

      // Plugin Settings
      // --------------------------------------------------
      mpSettings.SetValue("#Plugin","music_folder",music_tb.Text);
      mpSettings.SetValue("#Plugin", "video_folder", video_tb.Text);
      mpSettings.SetValueAsBool("#Plugin", "move_files",do_move_chk.Checked); 
      // --------------------------------------------------
      //SAVE HELLANZB CONFIG FILE
      StreamWriter Hell_Conf_Write = new StreamWriter(hella_tb.Text+@"\system\etc\hellanzb.conf");
      for (int i = 0; i < FILE.Count; i++)
      {
        if (FILE[i].ToString().IndexOf("defineServer") > -1)
        {
          string REPLACED = Regex.Replace(this.FILE[i].ToString(), @"defineServer\(.*?\)", "defineServer(id='newsserver', hosts=['"+server_tb.Text+":"+port_tb.Text+"'],username='"+user_tb.Text+"', password='"+pwd_tb.Text+"', connections="+connections_combox.SelectedItem+", antiIdle = 4.5*60, ssl="+enable_ssl_chk.Checked.ToString()+")");
          Hell_Conf_Write.WriteLine(REPLACED);
          continue;
        }
        else
        {
          Hell_Conf_Write.WriteLine(FILE[i].ToString());
        }
      }
      
      Hell_Conf_Write.Close();

      //########## write filters ##############
      string AUTO_MOVIE = String.Empty;
      string AUTO_REMOVE = String.Empty;
      for (int i = 0; i < movie_filter_lb.Items.Count; i++) {
        if (i == movie_filter_lb.Items.Count) AUTO_MOVIE = AUTO_MOVIE + movie_filter_lb.Items[i];
        else {AUTO_MOVIE = AUTO_MOVIE + movie_filter_lb.Items[i]+";"; }
      }
      for (int i = 0; i < auto_remove_lb.Items.Count; i++) {
        if (i == auto_remove_lb.Items.Count) { AUTO_REMOVE = AUTO_REMOVE + auto_remove_lb.Items[i]; }
        else { AUTO_REMOVE = AUTO_REMOVE + auto_remove_lb.Items[i] + ";"; }
      }
      mpSettings.SetValue("#Filters", "auto_movie", AUTO_MOVIE);
      mpSettings.SetValue("#Filters", "auto_remove", AUTO_REMOVE);
      mpSettings.Dispose();

    }

    private void btnOK_Click(object sender, EventArgs e)
    {
      SaveConfig();
      this.Close();
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    private void Hella_Btn_Click(object sender, EventArgs e)
    {
      FolderBrowserDialog dlg = new FolderBrowserDialog();
 
      if (dlg.ShowDialog() == DialogResult.OK)
      {
        hella_tb.Text = dlg.SelectedPath;

      }
    }

    private void music_btn_Click(object sender, EventArgs e)
    {
      FolderBrowserDialog dlg = new FolderBrowserDialog();

      if (dlg.ShowDialog() == DialogResult.OK)
      {
        music_tb.Text = dlg.SelectedPath;
        

      }
    }

    private void button1_Click(object sender, EventArgs e)
    {
      FolderBrowserDialog dlg = new FolderBrowserDialog();

      if (dlg.ShowDialog() == DialogResult.OK)
      {
        video_tb.Text = dlg.SelectedPath;


      }
    }

    private void kill_hell_btn_Click(object sender, EventArgs e)
    {
      foreach (System.Diagnostics.Process clsProcess in System.Diagnostics.Process.GetProcesses())
      {//get list of running processes
        if (clsProcess.ProcessName.IndexOf("pythonw") > -1 || clsProcess.ProcessName.IndexOf("python") > -1)
        {
          clsProcess.Kill(); //kill HellaNZB
          MessageBox.Show("HellaNZB (Pythonw.exe) Killed.");
          break;
        }
      }
    }

    private void auto_add_btn_Click(object sender, EventArgs e)
    {
      movie_filter_lb.Items.Add(auto_tb.Text);
      auto_tb.Text = String.Empty;
    }

    private void auto_remove_btn_Click(object sender, EventArgs e)
    {
      movie_filter_lb.Items.RemoveAt(movie_filter_lb.SelectedIndex);
      
    }

    private void Auto_Remove_Filter_Click(object sender, EventArgs e)
    {
      auto_remove_lb.Items.Add(auto_remove_tb.Text);
      auto_remove_tb.Text = String.Empty;
    }

    private void auto_rem_remove_btn_Click(object sender, EventArgs e)
    {
      auto_remove_lb.Items.RemoveAt(auto_remove_lb.SelectedIndex);
    }

   

    

    

   

    
  }
}